/*
 * This file (Utils.java) is protected by the GNU GPL licence (v2). 
 * Please read the license.txt attached for further informations. 
 * 
 */
package org.algoristes.alkwarel.script;

/**
 * @author Xavier Gouchet
 * 
 */
public class Utils {
	/**
	 * Given the index of an openning delimiter, finds the matching closing one.
	 * No test is made to check that the index indeed is an openning delimiter.
	 * 
	 * @param input
	 *            the string to analyse
	 * @param index
	 *            the index of an openning curly brace
	 * @param opening
	 *            the character corresponding to an openning delimiter (ie : [)
	 * @param closing
	 *            the character corresponding to a closing delimiter (ie : ])
	 * @return the index of the matching closing brace
	 */
	public static int getMatchingDelimiter(String input, int index,
			char opening, char closing) {
		int depth, open, close;
		depth = 1;

		do {
			open = input.indexOf(opening, index + 1);
			close = input.indexOf(closing, index + 1);

			if ((open < close) && (open != -1)) {
				depth++;
				index = open;
			}

			if ((close != -1) && ((close < open) || (open == -1))) {
				depth--;
				index = close;
			}
		} while ((depth != 0) && (close != -1));

		return close;
	}

	/**
	 * Searches into a string the first index of an unescaped double quote
	 * character, meaning a double quote character not preceded by a backslash
	 * character
	 * 
	 * @param input
	 *            the string to analyse
	 * @param index
	 *            the index to start from
	 * @return the index of the first unescaped double quote starting from the
	 *         given index
	 */
	public static int getIndexOfUnescapedDoubleQuote(String input, int index) {
		int dblQuote, backSlash;
		dblQuote = input.indexOf('"', index);
		backSlash = input.indexOf('\\');
		while ((dblQuote != -1) && (backSlash != -1)
				&& (backSlash == dblQuote - 1)) {
			backSlash = input.indexOf('\\', dblQuote + 1);
			dblQuote = input.indexOf('"', dblQuote + 1);
		}
		return dblQuote;
	}

	/**
	 * 
	 * @param str
	 * @param index
	 * @param length
	 * @return a substring of max size length from index
	 */
	public static String getNeighbourHood(String str, int index, int length) {
		if (str.length() < index + length)
			return str.substring(index, str.length());

		return str.substring(index, index + length);
	}
}
